﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Josse.Components
{
    public abstract class Sprite
    {
        //public
        Texture2D texture;   
        Point currentFrame;
        Point sheetSize;

        int timeSinceLastFrame = 0;
        int millisecondsPerFrame;

        const int defaultMsPerFrame = 16;
        //protected
        protected Vector2 speed;
        protected Vector2 position;
        protected Point frameSize;

        public Sprite(Texture2D textureImage, Vector2 position, Point frameSize,
                      Point currentFrame, Point sheetSize, Vector2 speed)
            : this(textureImage, position, frameSize, currentFrame,
                   sheetSize, speed, defaultMsPerFrame)
        {
        }

        public Sprite(Texture2D textureImage, Vector2 position, Point frameSize,
                      Point currentFrame, Point sheetSize, Vector2 speed, int millisecondsPerFrame)
        {
            this.texture = textureImage;
            this.position = position;
            this.frameSize = frameSize;
            this.currentFrame = currentFrame;
            this.sheetSize = sheetSize;
            this.speed = speed;
            this.millisecondsPerFrame = millisecondsPerFrame;
        }

        public virtual void Update(GameTime gameTime, Rectangle clientBounds)
        {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
            if (timeSinceLastFrame > millisecondsPerFrame)
            {
                timeSinceLastFrame = 0;
                ++currentFrame.X;
                if (currentFrame.X >= sheetSize.X)
                {
                    currentFrame.X = 0;
                    ++currentFrame.Y;
                    if (currentFrame.Y > sheetSize.Y)
                    {
                        currentFrame.Y = 0;
                    }
                }
            }
        }

        public virtual void Draw(GameTime gameTime, SpriteBatch sprBatch)
        {
            sprBatch.Draw(texture,
                          position,
                          new Rectangle(currentFrame.X * frameSize.X,
                                        currentFrame.Y * frameSize.Y,
                                        frameSize.X,
                                        frameSize.Y),
                          Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0);
        }

        public abstract Vector2 Direction
        {
            get;
        }

        public Rectangle CollisionRect
        {
            get
            {
                return new Rectangle((int)position.X,
                                     (int)position.Y,
                                     frameSize.X,
                                     frameSize.Y);
            }
        }
    }
}
